package com.pancm.web;

import com.pancm.datacollector.collector.Collector;
import com.pancm.datacollector.collector.CollectorStatus;
import com.pancm.datacollector.config.ConfigurationManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 数据采集控制器
 * 提供HTTP接口用于控制数据采集任务的执行
 * 所有接口都需要Basic认证
 *
 * @author zzl
 * @version 1.0
 * @date 2024-01-01
 */
@RestController
public class DataController {
    private static Logger LOG = LoggerFactory.getLogger(DataController.class);
    @Autowired
    private Collector collector;  // 注入当前使用的采集器实例

    /**
     * 控制采集任务的接口
     *
     * @param action 控制命令，支持以下操作：
     *              - start: 启动采集任务
     *              - stop: 停止采集任务
     *              - restart: 重启采集任务
     *              - collect: 执行一次手动采集
     *              - status: 查询采集器状态
     * @return ResponseEntity<String> 包含操作结果的响应实体
     *         - 200 OK: 操作成功
     *         - 400 Bad Request: 无效的命令
     *         - 401 Unauthorized: 未提供认证信息或认证失败
     *         - 500 Internal Server Error: 执行命令时发生错误
     *
     * @throws Exception 执行命令过程中可能抛出的异常
     *
     * @example
     * GET /collector/control?action=start
     * Headers: 
     *   Authorization: Basic YWRtaW46YWRtaW4xMjM=
     * Response: {"采集任务已启动"}
     * 
     * GET /collector/control?action=status
     * Response: {
     *   "status": "RUNNING",
     *   "message": "采集器正在运行中"
     * }
     */
    @RequestMapping("/collector/control")
    public ResponseEntity<String> controlCollector(@RequestParam String action) {
        LOG.info("收到采集控制命令: {}", action);

        try {
            switch (action.toLowerCase()) {
                case "start":
                    collector.start();
                    LOG.info("启动采集任务成功");
                    return new ResponseEntity<>("采集任务已启动", HttpStatus.OK);

                case "stop":
                    collector.stop();
                    LOG.info("停止采集任务成功");
                    return new ResponseEntity<>("采集任务已停止", HttpStatus.OK);

                case "restart":
                    collector.restart();
                    LOG.info("重启采集任务成功");
                    return new ResponseEntity<>("采集任务已重启", HttpStatus.OK);

                case "collect":
                    collector.collectToQueue();
                    LOG.info("手动执行采集任务成功");
                    return new ResponseEntity<>("手动采集成功", HttpStatus.OK);
                    
                case "status":
                    CollectorStatus status = collector.getStatus();
                    String statusMessage = getStatusMessage(status);
                    LOG.info("查询采集器状态: {}", status);
                    return new ResponseEntity<>(statusMessage, HttpStatus.OK);

                default:
                    return new ResponseEntity<>("无效的命令，支持的命令：start, stop, restart, collect, status",
                            HttpStatus.BAD_REQUEST);
            }
        } catch (Exception e) {
            LOG.error("执行采集控制命令时发生错误", e);
            return new ResponseEntity<>("执行命令时发生错误: " + e.getMessage(),
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 获取状态描述信息
     */
    private String getStatusMessage(CollectorStatus status) {
        StringBuilder message = new StringBuilder();
        message.append("{ \"status\": \"").append(status.name()).append("\", ");
        message.append("\"message\": \"");
        
        switch (status) {
            case UNINIT:
                message.append("采集器未初始化");
                break;
            case RUNNING:
                message.append("采集器正在运行中");
                break;
            case STOPPED:
                message.append("采集器已停止");
                break;
            case ERROR:
                message.append("采集器处于错误状态");
                break;
            default:
                message.append("未知状态");
        }
        
        message.append("\" }");
        return message.toString();
    }
}
